package pos;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.qmuiteam.qmui.widget.dialog.QMUIDialog;
import com.qmuiteam.qmui.widget.popup.QMUIPopup;

import net.ck.hzq.R;
import net.ck.hzq.RecognizeService;

import java.io.File;
import java.util.Arrays;

import Bean.PhoneNumerBean;
import Bean.PhoneNumerParamBean;
import Utils.FileUtil;
import Utils.HelloWordModel;
import Utils.OCRUtils;
import Utils.ScreenUtil;
import Utils.SharedPrefStore;
import Utils.SystemDatas;
import Utils.ToastUtil;
import activity.VerifyingActivity;
import activity.glide.GlideApp;
import base.BaseActivity;
import dao.AddPosInput;
import dao.BaseOutput;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import ui.activity.profit.biz.ProfitBiz;
import util.LogUtils;
import util.PermissionUtils;
import widget.CitySelectView;
import widget.DarkPopup;

import static Utils.FileUtil.compress;
import static com.qmuiteam.qmui.widget.popup.QMUIPopup.DIRECTION_BOTTOM;

/**
 * by BF00233 on 2018/12/15.
 */
public class OldPosAuthActivity extends BaseActivity implements View.OnClickListener {

    private static final int REQUEST_CODE_PICK_IMAGE_FRONT = 201;
    private static final int REQUEST_CODE_PICK_IMAGE_BACK = 202;
    private static final int REQUEST_CODE_FACE = 203;
    private static final int REQUEST_CODE_CAMERA = 102;
    private static final int REQUEST_CODE_BANKCARD = 111;
    private static final int REQUEST_CODE_BANKCARD_BACK = 112;
    private static final int REQUEST_CODE_BUSINESS_LICENSE = 113;
    private static final int REQUEST_CODE_DOOR = 114;
    private static final int REQUEST_CODE_ENVIRONMENT = 115;

    private CountDownTimer timer;
    private String mCode;

    // 1-扫描身份证正面 2-身份证反面 3-确认身份证信息　4-手持认证 ５-银行卡正面，6-银行卡背面 7-填写所有信息
    private int mStep = 1;

    // 身份证信息
    private String mIdAddress, mIdName, mIdNo, mIdGender, mIdDate;
    // 银行卡信息
    private String cardNum, cardType, cardBank, cardVerificationCode;
    // 照片缓存路径
    private String mImagePathIdFront, mImagePathIdBack, mImagePathHand,
            mImagePathBankCard, mImagePathBankCardBack, mImagePathBusinessLicense;
    // 照片 base64 数据
    private String base64_id_front, base64_id_back, base64_hand, base64_back_card,
            base64_back_card_back, base64_business_license, base64_door, base64_environment;

    private ScrollView scrollView;
    private Button mAuthBtn;
    private TextView warnTip;
    private ViewGroup imageLayout;
    private ImageView authImage;
    private String ratenum;//费率
    // 顶部　当前步骤
    private ImageView sm_back, sm_title_img1, sm_title_img2, sm_title_img3, sm_title_img4;
    private TextView sm_title_txt1, sm_title_txt2, sm_title_txt3, sm_title_txt4;
    private View sm_title_vw1, sm_title_vw2, sm_title_vw3;
    private ImageView ivAdd;//顶部更多按钮

    private ViewGroup sm_linear1;
    private AppCompatEditText sm_linear1_txt1, sm_linear1_txt2, sm_linear1_txt3, sm_linear1_txt4;
    // 详细信息填写
    private ViewGroup detailInfoLayout;
    private ImageView idFrontIv, idBackIv, holdIv, bankCardIv, bankCardBackIv, businessLicenseIv;
    private TextView detailIdNo, detailIdName;
    private AppCompatEditText bankCardNameEt, bankCardNoEt, phoneEt, verifyCodeEt, snEt,
            openAccountBankEt, detailAddressEt, emailEt;
    // 门头照，环境照
    private ViewGroup extraImageLayout;
    private ImageView doorIv, environmentIv;

    private TextView merchantTypeTv,tv_rate,auto_scan_sn;
    // 验证码
    private TextView getVerifyCode;

    private CitySelectView citySelectView;
    private RelativeLayout rate_layout;
    private String mAddressCode;
    private TextView addressSelectTv;
    ProfitBiz profitBiz;
    private String mMerchantType;

    //申请权限
    private final String[] PERMISSIONS = new String[]{Manifest.permission.CAMERA,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,

    };
    private final int REQUEST_WRITE = 2;
    public static void start(Context context) {
        Intent intent = new Intent(context, OldPosAuthActivity.class);
        context.startActivity(intent);
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_old_pos_auth;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        profitBiz = new ProfitBiz();
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
        } else {
            requestMorePermissions();
        }
        scrollView = findViewById(R.id.scroll_view);
        mAuthBtn = findViewById(R.id.auth_btn);
        imageLayout = findViewById(R.id.image_layout);
        authImage = findViewById(R.id.auth_image);
        warnTip = findViewById(R.id.warn_tip);
        sm_back = findViewById(R.id.sm_back);
        // 顶部步骤条
        sm_title_img1 = findViewById(R.id.sm_title_img1);
        sm_title_img2 = findViewById(R.id.sm_title_img2);
        sm_title_img3 = findViewById(R.id.sm_title_img3);
        sm_title_img4 = findViewById(R.id.sm_title_img4);
        sm_title_txt1 = findViewById(R.id.sm_title_txt1);
        sm_title_txt2 = findViewById(R.id.sm_title_txt2);
        sm_title_txt3 = findViewById(R.id.sm_title_txt3);
        sm_title_txt4 = findViewById(R.id.sm_title_txt4);
        sm_title_vw1 = findViewById(R.id.sm_title_vw1);
        sm_title_vw2 = findViewById(R.id.sm_title_vw2);
        sm_title_vw3 = findViewById(R.id.sm_title_vw3);
        rate_layout = findViewById(R.id.rate_layout);
        ivAdd = findViewById(R.id.iv_add);
        auto_scan_sn = findViewById(R.id.auto_scan_sn);
        sm_linear1 = findViewById(R.id.sm_linear1);
        sm_linear1_txt1 = findViewById(R.id.sm_linear1_txt1);
        sm_linear1_txt2 = findViewById(R.id.sm_linear1_txt2);
        sm_linear1_txt3 = findViewById(R.id.sm_linear1_txt3);
        sm_linear1_txt4 = findViewById(R.id.sm_linear1_txt4);

        // 详细信息
        detailInfoLayout = findViewById(R.id.detail_info_layout);
        detailIdNo = findViewById(R.id.detail_id_no);
        detailIdName = findViewById(R.id.detail_id_name);

        bankCardNameEt = findViewById(R.id.et_bank_card_name);
        bankCardNoEt = findViewById(R.id.et_bank_card_no);
        phoneEt = findViewById(R.id.et_merchant_phone);
        verifyCodeEt = findViewById(R.id.et_verify_code);
        snEt = findViewById(R.id.et_sn);
        addressSelectTv = findViewById(R.id.address_input);
        merchantTypeTv = findViewById(R.id.merchant_type);
        openAccountBankEt = findViewById(R.id.et_open_account_bank);
        detailAddressEt = findViewById(R.id.et_address);
        emailEt = findViewById(R.id.et_email);

        idFrontIv = findViewById(R.id.image_id_card_front);
        idBackIv = findViewById(R.id.image_id_card_back);
        holdIv = findViewById(R.id.image_hold);
        bankCardIv = findViewById(R.id.image_bank_card);
        bankCardBackIv = findViewById(R.id.image_bank_card_back);
        businessLicenseIv = findViewById(R.id.image_business_license);
        tv_rate = findViewById(R.id.tv_rate);
        extraImageLayout = findViewById(R.id.extra_image_layout);
        doorIv = findViewById(R.id.image_door);
        environmentIv = findViewById(R.id.image_environment);

        // 验证码
        getVerifyCode = findViewById(R.id.get_verify_code);
        getVerifyCode.setOnClickListener(this);

        mAuthBtn.setOnClickListener(this);
        businessLicenseIv.setOnClickListener(this);
        doorIv.setOnClickListener(this);
        environmentIv.setOnClickListener(this);
        sm_back.setOnClickListener(this);
        ivAdd.setOnClickListener(this);
        auto_scan_sn.setOnClickListener(this);
        rate_layout.setOnClickListener(this);
        // 商户类型选择
        findViewById(R.id.merchant_type_layout).setOnClickListener(this);

        // 地址选择
        findViewById(R.id.address_layout).setOnClickListener(this);
        citySelectView = findViewById(R.id.city_select_view);
        citySelectView.setAddressSelectedListener((code, address) -> {
            mAddressCode = code;
            citySelectView.setVisibility(View.GONE);
            addressSelectTv.setText(address);
            addressSelectTv.setTextColor(getResources().getColor(R.color.tc_666666));
            LogUtils.d("+++++11111省市地址数据+++++++++++" + address);
        });
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.auth_btn:
                doNextAuth();
                break;
            case R.id.image_business_license:
                OCRUtils.startBusinessLicense(this, REQUEST_CODE_BUSINESS_LICENSE);
                break;
            case R.id.address_layout:
                citySelectView.setVisibility(View.VISIBLE);
                break;
            case R.id.merchant_type_layout:
                showSelectBankTypeDialog();
                break;
            case R.id.image_door:
                OCRUtils.startCapture(this, FileUtil.getDoor(this), REQUEST_CODE_DOOR);
                break;
            case R.id.image_environment:
                OCRUtils.startCapture(this, FileUtil.getEnvironment(this), REQUEST_CODE_ENVIRONMENT);
                break;
            case R.id.get_verify_code:
                requestVerifyCode();
                break;
            case R.id.iv_add:
                showPopupMenu();
                break;
            case R.id.sm_back:
                finish();
                break;
            case R.id.auto_scan_sn:
                IntentIntegrator integrator = new IntentIntegrator(OldPosAuthActivity.this);
                // 设置要扫描的条码类型，ONE_D_CODE_TYPES：一维码，QR_CODE_TYPES-二维码
                integrator.setDesiredBarcodeFormats(IntentIntegrator.ONE_D_CODE_TYPES);
                integrator.setCaptureActivity(ScanActivity.class); //设置打开摄像头的Activity
                integrator.setPrompt("请扫描SN"); //底部的提示文字，设为""可以置空
                integrator.setCameraId(0); //前置或者后置摄像头
                integrator.setBeepEnabled(true); //扫描成功的「哔哔」声，默认开启
                integrator.setBarcodeImageEnabled(true);
                integrator.initiateScan();
                break;
            case R.id.rate_layout:
//                profitBiz.GetUserRate2(new BaseBiz.Callback<List<String>>() {
//                    @Override
//                    public void onSuccess(List<String> info) {
//                        String[] items = new String[info.size()];
//                        for (int i = 0;i<info.size();i++){
//                            items[i]=info.get(i);
//                        }
//                        new QMUIDialog.CheckableDialogBuilder(OldPosAuthActivity.this)
//                                .addItems(items, (dialogInterface, i) -> {
//                                    ratenum = items[i];
//                                    tv_rate.setText(ratenum);
//                                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
//                                    dialogInterface.dismiss();
//                                })
//                                .create()
//                                .show();
//
//                    }
//
//                    @Override
//                    public void onFailure(List<String> info) {
//
//                    }
//                });
//                SharedPrefStore store = new SharedPrefStore();
//                String   customId = store.getString("id", "0");
//                profitBiz.GetUserRate(customId ,new BaseBiz.Callback<RateLevelBean>() {
//                    @Override
//                    public void onSuccess(RateLevelBean info) {
//
//                        if(info.getLevelAmount()<=5){
//                            showLevelRate();
//                        }else{
//                            showLevelRate2();
//                        }
//
//                    }
//
//                    @Override
//                    public void onFailure(RateLevelBean info) {
//
//                    }
//                });
                break;
        }
    }
    //level<=3
    private void showLevelRate() {
        String[] items = new String[]{"0.60%","0.61%","0.62%","0.63%","0.64%","0.65%"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    ratenum = items[i];
                    tv_rate.setText(ratenum);
                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }
    //level>=43
    private void showLevelRate2() {
        String[] items = new String[]{"0.55%","0.56%","0.57%","0.58%","0.59%","0.60%","0.61%","0.62%","0.63%","0.64%","0.65%"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    ratenum = items[i];
                    tv_rate.setText(ratenum);
                    tv_rate.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }

    private void showSelectBankTypeDialog() {
        String[] items = new String[]{"餐娱类", "民生类", "一般类", "公益类", "房产汽车类"};
        new QMUIDialog.CheckableDialogBuilder(this)
//                .setCheckedIndex(Arrays.binarySearch(items, mMerchantType))
                .addItems(items, (dialogInterface, i) -> {
                    mMerchantType = items[i];
                    merchantTypeTv.setText(mMerchantType);
                    merchantTypeTv.setTextColor(getResources().getColor(R.color.tc_666666));
                    dialogInterface.dismiss();
                })
                .create()
                .show();
    }

    private void doNextAuth() {
        if (mStep == 1) {
            OCRUtils.startIDCardFront(this, REQUEST_CODE_PICK_IMAGE_FRONT);
        } else if (mStep == 2) {
            OCRUtils.startIDCardBack(this, REQUEST_CODE_PICK_IMAGE_BACK);
        } else if (mStep == 3) {
            if (TextUtils.isEmpty(sm_linear1_txt1.getText())
                    || TextUtils.isEmpty(sm_linear1_txt2.getText())
                    || TextUtils.isEmpty(sm_linear1_txt3.getText())
                    || TextUtils.isEmpty(sm_linear1_txt4.getText())) {
                Toast.makeText(OldPosAuthActivity.this, "请输入身份证信息", Toast.LENGTH_SHORT).show();
                return;
            }
            warnTip.setText("请正对手机，确保光线充足，并确保是本人操作。");
            mAuthBtn.setText("拍照");
            authImage.setImageResource(R.drawable.rlsb);
            authImage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
            sm_linear1.setVisibility(View.GONE);
            sm_title_img1.setImageResource(R.drawable.rzwc);
            sm_title_img2.setImageResource(R.drawable.rzz);
            sm_title_txt2.setTextColor(getResources().getColor(R.color.colorBlue));
            sm_title_vw1.setBackgroundColor(getResources().getColor(R.color.colorBlue));
            mStep = 4;
        } else if (mStep == 4) {
            OCRUtils.startFace(this, REQUEST_CODE_FACE);
        } else if (mStep == 5) {
            OCRUtils.startBankCard(this, REQUEST_CODE_BANKCARD);
        } else if (mStep == 6) {
            OCRUtils.startBankCardBack(this, REQUEST_CODE_BANKCARD_BACK);
        } else if (mStep == 7) {
            submitData();
        }
    }

    private void submitData() {
        if (!checkDetailInput()) {
            showFailureTipDialog("请输入所有必要信息");
            return;
        }
        showProgressDialog();
        SharedPrefStore store = new SharedPrefStore();
        AddPosInput param = new AddPosInput();
        param.customId = store.getString("id", "0");
        param.merchantName = sm_linear1_txt1.getText().toString();
        param.idCard = sm_linear1_txt3.getText().toString();
        param.phone = phoneEt.getEditableText().toString();
        param.bankCardNumber = bankCardNoEt.getEditableText().toString();
        param.bank = bankCardNameEt.getEditableText().toString();
        param.sn =  snEt.getEditableText().toString().trim().replace("\n","");
        param.region = mAddressCode;
        param.address = detailAddressEt.getEditableText().toString();
        param.qqemail = emailEt.getEditableText().toString();
        param.rate = tv_rate.getText().toString().replace("%","");
        param.idCardFront = base64_id_front;
        param.idCardBack = base64_id_back;
        param.holdIdCardFront = base64_hand;
        param.bankFont = base64_back_card;
        param.bankBack = base64_back_card_back;
        if (!TextUtils.isEmpty(base64_business_license)) {
            param.businessLicense = base64_business_license;
            param.door = base64_door;
            param.businessment = base64_environment;
        }
        param.khzh = openAccountBankEt.getEditableText().toString();
        param.businessType = mMerchantType;

        Call<BaseOutput<Object>> userMsgCall = HelloWordModel.getInstance(OldPosAuthActivity.this)
                .addTraditionalPos(param);
        userMsgCall.enqueue(new Callback<BaseOutput<Object>>() {
            @Override
            public void onResponse(@NonNull Call<BaseOutput<Object>> call, @NonNull Response<BaseOutput<Object>> response) {

                dismissProgressDialog();
                try{
                if (response.body() != null) {
                    if ("success".equals(response.body().msg)) {
                        VerifyingActivity.start(OldPosAuthActivity.this);
                        finish();
                    } else {
                        showFailureTipDialog(response.body().msg);
                    }
                }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(@NonNull Call<BaseOutput<Object>> call, @NonNull Throwable t) {
                dismissProgressDialog();
                ToastUtil.show(OldPosAuthActivity.this, "提交失败，请稍后重试");
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(null!=timer){
            timer.cancel();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 人脸拍摄
        if (requestCode == REQUEST_CODE_FACE && resultCode == Activity.RESULT_OK) {
            handleFaceSuccess();
        }else
        // 银行卡
        if (requestCode == REQUEST_CODE_BANKCARD && resultCode == Activity.RESULT_OK) {
            reBankCard();
        }else
        // 银行卡背面
        if (requestCode == REQUEST_CODE_BANKCARD_BACK && resultCode == Activity.RESULT_OK) {
            handleBankBackSuccess();
        }else
        // 营业执照
        if (requestCode == REQUEST_CODE_BUSINESS_LICENSE && resultCode == Activity.RESULT_OK) {
            handleBusinessSuccess();
        }else
        // 门头照
        if (requestCode == REQUEST_CODE_DOOR && resultCode == Activity.RESULT_OK) {
            handleDoorSuccess();
        }else
        // 营业环境
        if (requestCode == REQUEST_CODE_ENVIRONMENT && resultCode == Activity.RESULT_OK) {
            handleEnvironmentSuccess();
        }else{
            IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (scanResult != null) {
                String result = scanResult.getContents();
                snEt.setText(result);
            }
        }
    }


    private void handleFaceSuccess() {
        mImagePathHand = FileUtil.getSaveFileFace(this).getAbsolutePath();
        base64_hand = "data:image/png;base64," + compress(mImagePathHand);
        authImage.setImageResource(R.drawable.bank);
        authImage.setScaleType(ImageView.ScaleType.FIT_XY);
        mAuthBtn.setText("扫描结算银行卡");
        sm_title_img2.setImageResource(R.drawable.rzwc);
        sm_title_img3.setImageResource(R.drawable.rzz);
        sm_title_txt3.setTextColor(getResources().getColor(R.color.colorBlue));
        sm_title_vw2.setBackgroundColor(getResources().getColor(R.color.colorBlue));
        mStep = 5;
        showSuccessTipDialog("拍照成功!请扫描银行卡");
    }

    private void handleBankBackSuccess() {
        mStep = 7;
        mImagePathBankCardBack = FileUtil.getBankBackFile(this).getAbsolutePath();
        base64_back_card_back = "data:image/png;base64," + compress(mImagePathBankCardBack, 1000);
        imageLayout.setVisibility(View.GONE);
        sm_title_img3.setImageResource(R.drawable.rzwc);
        sm_title_img4.setImageResource(R.drawable.rzz);
        sm_title_txt4.setTextColor(getResources().getColor(R.color.colorBlue));
        sm_title_vw3.setBackgroundColor(getResources().getColor(R.color.colorBlue));

        detailIdName.setText(sm_linear1_txt1.getText().toString());
        detailIdNo.setText(sm_linear1_txt3.getText().toString());
        bankCardNameEt.setText(cardBank);
        bankCardNoEt.setText(cardNum);
        GlideApp.with(detailInfoLayout)
                .load(mImagePathIdFront)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(idFrontIv);
        GlideApp.with(detailInfoLayout)
                .load(mImagePathIdBack)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(idBackIv);
        GlideApp.with(detailInfoLayout)
                .load(mImagePathHand)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(holdIv);
        GlideApp.with(detailInfoLayout)
                .load(mImagePathBankCard)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(bankCardIv);
        GlideApp.with(detailInfoLayout)
                .load(mImagePathBankCardBack)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .into(bankCardBackIv);

        detailInfoLayout.setVisibility(View.VISIBLE);
        scrollView.setFocusable(true);
        scrollView.requestFocus();
        mAuthBtn.setText("确认提交");
        warnTip.setText("");
    }

    private void handleBusinessSuccess() {
        mImagePathBusinessLicense = FileUtil.getBusinessLicense(this).getAbsolutePath();
        base64_business_license = "data:image/png;base64," + compress(mImagePathBusinessLicense);
        GlideApp.with(this)
                .load(mImagePathBusinessLicense)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(businessLicenseIv);
        businessLicenseIv.setScaleType(ImageView.ScaleType.FIT_XY);

        extraImageLayout.setVisibility(View.VISIBLE);
    }

    private void handleDoorSuccess() {
        String path = FileUtil.getDoor(this).getAbsolutePath();
        base64_door = "data:image/png;base64," + compress(path);
        GlideApp.with(this)
                .load(path)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(doorIv);
        doorIv.setScaleType(ImageView.ScaleType.FIT_XY);
    }

    private void handleEnvironmentSuccess() {
        String path = FileUtil.getEnvironment(this).getAbsolutePath();
        base64_environment = "data:image/png;base64," + compress(path);
        GlideApp.with(this)
                .load(path)
                .diskCacheStrategy(DiskCacheStrategy.NONE)
                .skipMemoryCache(true)
                .into(environmentIv);
        environmentIv.setScaleType(ImageView.ScaleType.FIT_XY);
    }

    private void reBankCard() {
    }

    private void requestVerifyCode() {
        if (TextUtils.isEmpty(phoneEt.getText()) || TextUtils.isEmpty(phoneEt.getText().toString().trim())) {
            ToastUtil.showNormal(this, "请输入手机号码");
            return;
        }
        if (timer != null) {
            timer.cancel();
        }
        getVerifyCode.setEnabled(false);
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                getVerifyCode.setText(l / 1000 + "秒后重发");
            }

            @Override
            public void onFinish() {
                getVerifyCode.setEnabled(true);
                getVerifyCode.setText("获取验证码");
            }
        };
        timer.start();

        String phone = phoneEt.getText().toString().trim();
        PhoneNumerParamBean p = new PhoneNumerParamBean();
        p.setTelephoneNumber(phone);
        Call<PhoneNumerBean> userMsgCall2 = HelloWordModel.getInstance(this).getphonecode(SystemDatas.GetService_URL
                ("getphonecode2"), p);
        userMsgCall2.enqueue(new retrofit2.Callback<PhoneNumerBean>() {
            @Override
            public void onResponse(Call<PhoneNumerBean> call, final Response<PhoneNumerBean> response) {
              try{
                if (response.body() != null && response.body().getMsg().equals("success")) {
                    ToastUtil.showNormal(OldPosAuthActivity.this, "获取成功!");
                    mCode = response.body().getData().getCode();
                } else {
                    ToastUtil.showNormal(OldPosAuthActivity.this, response.body().getMsg());
                }
              } catch (Exception e) {
                  e.printStackTrace();
              }
            }

            @Override
            public void onFailure(Call<PhoneNumerBean> call, Throwable t) {
                ToastUtil.showNormal(OldPosAuthActivity.this, "获取失败");
            }
        });
    }

    @Override
    public void onBackPressed() {
        if (citySelectView.getVisibility() == View.VISIBLE) {
            citySelectView.setVisibility(View.GONE);
            return;
        }
        super.onBackPressed();
    }

    private boolean checkDetailInput() {
        if (TextUtils.isEmpty(mCode) || !TextUtils.equals(mCode, verifyCodeEt.getEditableText().toString())) {
            return false;
        }
        return !TextUtils.isEmpty(phoneEt.getEditableText().toString())
                && !TextUtils.isEmpty(bankCardNoEt.getEditableText().toString())
                && !TextUtils.isEmpty(bankCardNameEt.getEditableText().toString())
                && !TextUtils.isEmpty(snEt.getEditableText().toString())
                && !TextUtils.isEmpty(mAddressCode)
                && !TextUtils.isEmpty(base64_business_license)
                && !TextUtils.isEmpty(base64_door)
                && !TextUtils.isEmpty(base64_environment)
                && !TextUtils.isEmpty(detailAddressEt.getEditableText().toString())
                && !TextUtils.isEmpty(openAccountBankEt.getEditableText().toString())
                && !TextUtils.isEmpty(mMerchantType);
    }

    private void showPopupMenu() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.popup_posopen, null);
        QMUIPopup qmuiPopup = new DarkPopup(this, DIRECTION_BOTTOM);
        qmuiPopup.setContentView(inflate);
        qmuiPopup.setPopupLeftRightMinMargin(ScreenUtil.dip2px(this, 5));
        qmuiPopup.show(ivAdd);
        inflate.findViewById(R.id.handfill).setOnClickListener(v -> {
            qmuiPopup.dismiss();
            OldPosAuthByHandActivity.start(OldPosAuthActivity.this);
        });

        inflate.findViewById(R.id.selfdeclaration).setOnClickListener(v -> {
            qmuiPopup.dismiss();
            OldPosAuthByAutoMaticActivity.start(OldPosAuthActivity.this);
        });
        inflate.findViewById(R.id.applicationrecord).setOnClickListener(v -> {

            Intent intent = new Intent(OldPosAuthActivity.this,PosAutoRecordAct.class);
            startActivity(intent);
            qmuiPopup.dismiss();
        });
    }

    // 自定义申请多个权限
    private void requestMorePermissions() {
        PermissionUtils.checkMorePermissions(OldPosAuthActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
            @Override
            public void onHasPermission() {

            }

            @Override
            public void onUserHasAlreadyTurnedDown(String... permission) {
                showExplainDialog(permission, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.requestMorePermissions(OldPosAuthActivity.this, PERMISSIONS, REQUEST_WRITE);
                    }
                });
            }

            @Override
            public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                PermissionUtils.requestMorePermissions(OldPosAuthActivity.this, PERMISSIONS, REQUEST_WRITE);
            }
        });
    }


    /**
     * 解释权限的dialog
     */
    private void showExplainDialog(String[] permission, DialogInterface.OnClickListener onClickListener) {
        new AlertDialog.Builder(OldPosAuthActivity.this)
                .setTitle("申请权限")
                .setMessage("我们需要" + Arrays.toString(permission) + "权限")
                .setPositiveButton("确定", onClickListener)
                .show();
    }

    /**
     * 显示前往应用设置Dialog
     */
    private void showToAppSettingDialog() {
        new AlertDialog.Builder(OldPosAuthActivity.this)
                .setTitle("需要权限")
                .setMessage("我们需要相关权限，才能实现功能，点击前往，将转到应用的设置界面，请开启应用的相关权限。")
                .setPositiveButton("前往", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        PermissionUtils.toAppSetting(OldPosAuthActivity.this);
                    }
                })
                .setNegativeButton("取消", null).show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {

            case REQUEST_WRITE:
                PermissionUtils.onRequestMorePermissionsResult(OldPosAuthActivity.this, PERMISSIONS, new PermissionUtils.PermissionCheckCallBack() {
                    @Override
                    public void onHasPermission() {

                    }

                    @Override
                    public void onUserHasAlreadyTurnedDown(String... permission) {
                        Toast.makeText(OldPosAuthActivity.this, "我们需要获取拍照等权限", Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onUserHasAlreadyTurnedDownAndDontAsk(String... permission) {
                        Toast.makeText(OldPosAuthActivity.this, "我们需要获取拍照等权限", Toast.LENGTH_SHORT).show();
                        showToAppSettingDialog();
                    }
                });
        }
    }
}
